package net.labdemo.service.impl;

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.labdemo.dao.ArticleDao;
import net.labdemo.entity.Article;
import net.labdemo.service.ArticleService;

@Service
@Transactional(readOnly = true)
public class ArticleServiceImpl extends BaseEntityServiceSupport<Article,ArticleDao> implements ArticleService {

	@Autowired
	private ArticleDao articleDao;
	
	@Override
	public Article get(long id) {
		// TODO Auto-generated method stub
		return articleDao.get(id);
	}
	@Transactional(readOnly = false)
	@Override
	public long publish(Article article,long userId) {
		// TODO Auto-generated method stub
		if(article.getId()==0){
			return addArticle(article,userId);
		}else{
			return (editArticle(article)==1)?article.getId():0L;
		}
	}
	private long addArticle(Article article,long userId){
		long id=0L;
		article.setPubdate(new Date());
		article.setReadnum(1);
		System.out.println("[AS]author:"+article.getAuthor());
		
		articleDao.add(article);
		id=article.getId();
		System.out.println("[AS]add ID:"+id);
		if(id>0){
			articleDao.addContent(id, article.getContent());
		}
		return id;
	}
	private int editArticle(Article article){
		long id=article.getId();
		int affectArticle=articleDao.upd(article);
		int affectArticleContent=articleDao.updContent(id, article.getContent());
		System.out.println("[AS]edit affect:"+affectArticle+",content:"+affectArticleContent);
		return (affectArticleContent==1 && affectArticle==1)?1:-1;
	}
	/*
	 * 提取到BaseEntityServiceSupport
	@Override
	public Page<Article> selectPage(Article condition, Page<Article> page) {
		// TODO Auto-generated method stub
		//向着[数据库],主要附加cursor属性
		condition.setPage(page);
		System.out.println(condition.getPage());
		//向着[mvc],主要携带结果集和页码结构
		page.setResult(articleDao.findPage(condition));
		return page;
	}*/
}
